﻿using GsOrganization.Common.Extend;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading.Tasks;

namespace GsOrganization.Common.Helper
{
    public class SystemHelper
    {
        private static string DeviceCode = "";
        public static string GetDeviceCode()
        {
            if (DeviceCode.IsNullOrEmpty())
            {
                string hdid = GetDiskInfo()[0];
                string mbid = GetMainBoardId();
                DeviceCode = HashHandleHepler.SHA256((hdid.ToPureString() + mbid.ToPureString()).ToPureString().UTF8BytesFromString(), "123456".UTF8BytesFromString()).GetHexString();
            }
            return DeviceCode;
        }

        public static string GetMainBoardId()
        {
            ManagementClass mc = new ManagementClass("Win32_BaseBoard");
            var moc = mc.GetInstances();
            string pid = "";
            string sid = "";
            foreach (var info in moc)
            {
                foreach (var prop in info.Properties)
                {
                    if (prop.Name == "SerialNumber")
                        sid = prop.Value.ToString();
                    else if (prop.Name == "Product")
                        pid = prop.Value.ToString();
                }
            }
            return $"{pid}|{sid}";
        }

        public static List<string> GetDiskInfo()
        {
            ManagementClass mc = new ManagementClass("Win32_DiskDrive");
            var moc = mc.GetInstances();
            string did = "";
            List<string> res = new List<string>();
            foreach (var info in moc)
            {
                string model_id = "";
                string sid = "";
                bool isUsb = false;
                foreach (var prop in info.Properties)
                {
                    if (prop.Name == "InterfaceType")
                    {
                        if (prop.Value.ToString().ToUpper().IndexOf("USB") > -1)
                        {
                            isUsb = true;
                            break;
                        }
                    }
                    else if (prop.Name == "MediaType")
                    {
                        if (prop.Value.ToString().ToUpper().IndexOf("Removable".ToUpper()) > -1)
                        {
                            isUsb = true;
                            break;
                        }
                    }
                    else if (prop.Name == "Model")
                        model_id = prop.Value.ToString().ToPureString();
                    else if (prop.Name == "SerialNumber")
                        sid = prop.Value.ToString().ToPureString();
                }
                if (!isUsb)
                    res.Add($"{model_id}|{sid}");
            }
            return res;
        }
    }
}
